#include "stdafx.h"

#include <MyControls/SegmentSetRow.h>
#include <MyControls/Xline.h>
#include <MyControls/App.h>

#include <MyFC/Utility.h>
#include <xtd/functional>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

namespace My {

SegmentSetRow::SegmentSetRow(Xline & xline) :
	m_Xline(xline), m_pSegments(0)
{
	SetRowHeight(15);
}

SegmentSetRow::~SegmentSetRow()
{
	SetSegments(0);
}

void SegmentSetRow::SetSegments(SegmentSet * pSegments)
{
	if (m_pSegments == pSegments)
		return;
	if (m_pSegments != 0) {
		m_pSegments->GetDoc().Detach(this);
		m_pSegments->Detach(this);
	}
	m_pSegments = pSegments;
	if (m_pSegments != 0) {
		m_pSegments->Attach(this);
		m_pSegments->GetDoc().Attach(this);
		UpdateSegments();
		Expand();
	}
}

void SegmentSetRow::UpdateSegments()
{
	bool expanded = IsExpanded();
	TreeRow::Clear();
	xtd::for_each(m_SegmentRows, xtd::deleter());
	m_SegmentRows.clear();
	if (m_pSegments == 0)
		return;
	m_SegmentRows.reserve(m_pSegments->GetSegmentCount());
	std::vector<TreeRow *> rows;
	rows.reserve(m_pSegments->GetSegmentCount());
	for (My::Size i = 0; i < m_pSegments->GetSegmentCount(); ++i) {
		SegmentRow * pRow = new SegmentRow(* this, i);
		m_SegmentRows.push_back(pRow);
		rows.push_back(pRow);
	}
	TreeRow::Insert(0, &rows[0], rows.size());
	if (expanded && CanExpand())
		Expand();
}

void SegmentSetRow::SetCaption(const String & s)
{
	m_Caption = s;
	Invalidate();
}

String SegmentSetRow::GetCaption() const
{
	return m_Caption;
}

void SegmentSetRow::HandleLeftDown(unsigned int flags, const CPoint & p)
{
	TreeRow::HandleLeftDown(flags, p);
	GetApp().GetDoc().SetSelection(0);
}

void SegmentSetRow::HandlePaint(CDC * pDC, const CRect & rClip)
{
	CRect rClient = ClientRect();
	CPen pen(PS_SOLID, 1, GetSysColor(COLOR_BTNHILIGHT));
	pDC->SelectObject(&pen);
	pDC->MoveTo(rClient.left, rClient.bottom - 1);
	pDC->LineTo(rClient.right, rClient.bottom - 1);
	GridRow::HandlePaint(pDC, rClip);
}

void SegmentSetRow::PaintCell(CDC * pDC, const CRect & rClip, const Column & col, const CRect & rCell)
{
	if (&col == &m_Xline.GetNameCol())
		TreeRow::PaintCaption(pDC, rCell);
}

void SegmentSetRow::ProcessEvent(My::Event & e)
{
	if (e.Is<SegmentSet::Change>()) {
		UpdateSegments();
		Invalidate();
	} else
		Container::ProcessEvent(e);
}

} // My